package cn.iocoder.yudao.module.trade.order.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.business.order.pojo.vo.OrderSubmitVO;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.idempotent.core.annotation.Idempotent;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.UserIdempotentKeyResolver;
import cn.iocoder.yudao.framework.qrcode.pojo.QrCodeVerifyType;
import cn.iocoder.yudao.framework.qrcode.util.QrCodeUtils;
import cn.iocoder.yudao.module.api.dine.enums.DineStatusEnum;
import cn.iocoder.yudao.module.api.product.evaluation.ProductEvaluationApi;
import cn.iocoder.yudao.module.api.product.evaluation.dto.ProductEvaluationRespDTO;
import cn.iocoder.yudao.module.api.promotion.combination.CombinationRecordApi;
import cn.iocoder.yudao.module.api.promotion.groupon.GrouponPackageApi;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.api.shop.staff.ShopStaffApi;
import cn.iocoder.yudao.module.api.shop.staff.enums.ShopStaffRoleEnum;
import cn.iocoder.yudao.module.api.shop.staff.vo.ShopStaffVO;
import cn.iocoder.yudao.module.api.trade.delivery.enums.DeliveryTypeEnum;
import cn.iocoder.yudao.module.api.trade.order.dto.*;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeOrderStatusEnum;
import cn.iocoder.yudao.module.api.trade.order.vo.AppTradeOrderPageVO;
import cn.iocoder.yudao.module.trade.aftersale.service.AfterSaleService;
import cn.iocoder.yudao.module.trade.delivery.dal.dataobject.DeliveryExpressDO;
import cn.iocoder.yudao.module.trade.delivery.service.DeliveryExpressService;
import cn.iocoder.yudao.module.trade.framework.TradeOrderProperties;
import cn.iocoder.yudao.module.trade.order.convert.TradeOrderConvert;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import cn.iocoder.yudao.module.trade.order.service.TradeOrderQueryService;
import cn.iocoder.yudao.module.trade.order.service.TradeOrderUpdateService;
import cn.iocoder.yudao.module.trade.order.service.TradePriceService;
import cn.iocoder.yudao.module.trade.order.service.ZXHXOrderSyncService;
import cn.iocoder.yudao.module.trade.order.vo.*;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 App - 交易订单")
@RestController
@RequestMapping("/trade/order")
@Validated
@Slf4j
public class AppTradeOrderController implements TradeOrderStatusNameGetter {

    @Resource
    private TradeOrderUpdateService tradeOrderUpdateService;
    @Resource
    private TradeOrderQueryService tradeOrderQueryService;
    @Resource
    private DeliveryExpressService deliveryExpressService;
    @Resource
    private AfterSaleService afterSaleService;
    @Resource
    private TradePriceService tradePriceService;
    @Resource
    private ZXHXOrderSyncService zxhxOrderSyncService;

    @Resource
    private TradeOrderProperties tradeOrderProperties;

    @Resource
    private ShopInfoApi shopInfoApi;
    @Resource
    private ShopStaffApi shopStaffApi;
    @Resource
    private CombinationRecordApi combinationRecordApi;
    @Resource
    private ProductEvaluationApi productEvaluationApi;
    @Resource
    private GrouponPackageApi grouponPackageApi;

    @PostMapping("/settlement")
    @Operation(summary = "计算订单结算信息（买家）", description = "用于下单前确认，获得订单相关的价格信息")
    public CommonResult<AppTradeOrderSettlementRespVO> settlementOrder(@Valid @RequestBody AppTradeOrderSettlementReqVO reqVO) {
        AppTradeOrderSettlementRespVO respVO = tradeOrderUpdateService.settlementOrder(getLoginUserId(), reqVO);
        return success(respVO);
    }

    @PostMapping("/settlement-product")
    @Operation(summary = "计算产品结算信息", description = "用于产品列表、产品详情，获得参与活动后的价格信息")
    @PermitAll
    public CommonResult<List<AppTradeProductSettlementRespVO>> settlementProduct(@Valid @RequestBody AppTradeOrderSettlementProductReqVO reqVO) {
        List<AppTradeProductSettlementRespVO> respVOS = tradePriceService.calculateProductPrice(getLoginUserId(), reqVO.getSpuIds());
        return success(respVOS);
    }

    @Idempotent(timeout = 10, message = "订单已提交，请勿重复下单", keyResolver = UserIdempotentKeyResolver.class)
    @PostMapping("/create")
    @Operation(summary = "创建订单（买家）")
    public CommonResult<OrderSubmitVO> createOrder(@Valid @RequestBody AppTradeOrderCreateReqVO createReqVO) {
        TradeOrderDO order = tradeOrderUpdateService.createOrder(getLoginUserId(), createReqVO);
        OrderSubmitVO respVO = new OrderSubmitVO();
        respVO.setTradeNo(order.getNo());
        respVO.setPrice(order.getPayPrice());
        return success(respVO);
    }

    @GetMapping("/get-detail")
    @Operation(summary = "获得交易订单（买家）")
    public CommonResult<AppTradeOrderDetailRespVO> getOrderDetail(AppTradeOrderDetailReqVO reqVO) {
        // 1.1 查询订单
        TradeOrderDO order = null;
        if (reqVO.getId() != null && reqVO.getId() > 0) {
            order = tradeOrderQueryService.getOrder(getLoginUserId(), reqVO.getId());
        } else if (StrUtil.isNotEmpty(reqVO.getTradeNo())) {
            order = tradeOrderQueryService.getOrderByNo(getLoginUserId(), reqVO.getTradeNo());
        }
        return toOrderDetailRespVO(reqVO, order);
    }

    @GetMapping("/get-detail-seller")
    @Operation(summary = "获得交易订单（卖家）")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<AppTradeOrderDetailRespVO> getOrderDetailForSeller(AppTradeOrderDetailReqVO reqVO) {
        TradeOrderDO order = null;
        if (reqVO.getId() != null && reqVO.getId() > 0) {
            order = tradeOrderQueryService.getOrder(reqVO.getId());
        } else if (StrUtil.isNotEmpty(reqVO.getTradeNo())) {
            order = tradeOrderQueryService.getOrderByNo(reqVO.getTradeNo());
        }
        if (order != null) {
            // 校验权限，防止查看别的店铺的订单
            Long shopId = shopInfoApi.getShopIdByMemberUserId(getLoginUserId());
            Assertions.owner(order.getShopId(), shopId);
        }
        return toOrderDetailRespVO(reqVO, order);
    }

    @GetMapping("/get-detail-rider")
    @Operation(summary = "获得交易订单（配送员）")
    @PreAuthorize("@mm.isRider()")
    public CommonResult<AppTradeOrderDetailRespVO> getOrderDetailForRider(AppTradeOrderDetailReqVO reqVO) {
        TradeOrderDO order = null;
        if (reqVO.getId() != null && reqVO.getId() > 0) {
            order = tradeOrderQueryService.getOrder(reqVO.getId());
        } else if (StrUtil.isNotEmpty(reqVO.getTradeNo())) {
            order = tradeOrderQueryService.getOrderByNo(reqVO.getTradeNo());
        }
        if (order != null) {
            // 校验权限，防止查看别人的订单
            ShopStaffVO shopStaffVO = shopStaffApi.getByUserId(getLoginUserId(), UserTypeEnum.MEMBER.getValue(), ShopStaffRoleEnum.RIDER.getValue());
            Assertions.owner(order.getRiderStaffId(), shopStaffVO.getId());
        }
        return toOrderDetailRespVO(reqVO, order);
    }

    private CommonResult<AppTradeOrderDetailRespVO> toOrderDetailRespVO(AppTradeOrderDetailReqVO reqVO, TradeOrderDO order) {
        if (order == null) {
            return success(null);
        }
        if (CollUtil.isNotEmpty(order.getSupplyRelatedNos())) {
            for (String supplyRelatedNo : order.getSupplyRelatedNos()) {
                zxhxOrderSyncService.syncOrderInfoAsync(supplyRelatedNo, order);
            }
        }
        if (Boolean.TRUE.equals(reqVO.getSync())
            && TradeOrderStatusEnum.isUnpaid(order.getStatus()) && !order.getPayStatus()) {
            tradeOrderUpdateService.syncOrderPayStatusQuietly(order.getNo());
            // 重新查询，因为同步后，可能会有变化
            order = tradeOrderQueryService.getOrder(order.getId());
        }
        return toOrderDetailRespVO(order);
    }

    private CommonResult<AppTradeOrderDetailRespVO> toOrderDetailRespVO(TradeOrderDO order) {
        // 2.1 查询订单项
        List<TradeOrderItemDO> orderItems = tradeOrderQueryService.getOrderItemListByOrderId(order.getId());
        // 2.2 查询快递公司
        DeliveryExpressDO express = order.getLogisticsId() != null && order.getLogisticsId() > 0 ?
                deliveryExpressService.getDeliveryExpress(order.getLogisticsId()) : null;
        // 2.3 最终组合
        AppTradeOrderDetailRespVO data = TradeOrderConvert.INSTANCE.convert02(order, orderItems, tradeOrderProperties, express);
        data.setShop(shopInfoApi.getShopInfo(order.getShopId()));
        data.setStatusName(assignStatusName(order.getDeliveryType(), order.getStatus(), order.getCommentStatus(), order.getRefundStatus(), order.getDineStatus()));
        data.setRiderStaff(shopStaffApi.getById(order.getRiderStaffId()));
        if (data.getCombinationRecordId() != null && data.getCombinationRecordId() > 0) {
            data.setCombinationRecord(combinationRecordApi.getCombinationRecordById(data.getCombinationRecordId()));
        }
        if (data.getGrouponPackageId() != null && data.getGrouponPackageId() > 0) {
            data.setGrouponPackage(grouponPackageApi.getDetail(data.getGrouponPackageId()));
        }
        if (StrUtil.isNotBlank(order.getVerifyCode())) {
            QrCodeVerifyType type = new QrCodeVerifyType();
            type.setVerifyCode(order.getVerifyCode());
            data.setQrcode(QrCodeUtils.generatePngAsBase64Uri(type));
        }
        return success(data);
    }

    @GetMapping("/get-express-track-list")
    @Operation(summary = "获得交易订单的物流轨迹")
    @Parameter(name = "id", description = "订单编号")
    public CommonResult<List<AppOrderExpressTrackRespDTO>> getOrderExpressTrackList(@RequestParam("id") Long id) {
        return success(TradeOrderConvert.INSTANCE.convertList02(
                tradeOrderQueryService.getExpressTrackList(id, getLoginUserId())));
    }

    @GetMapping("/page")
    @Operation(summary = "获得交易订单分页（买家）")
    public CommonResult<PageResult<AppTradeOrderPageVO>> getOrderPage(AppTradeOrderPageReqVO reqVO) {
        Long userId = getLoginUserId();
        PageParam pageParam = new PageParam();
        pageParam.setPageNo(reqVO.getPageNo());
        pageParam.setPageSize(reqVO.getPageSize());
        TradeOrderQueryDTO queryDTO = new TradeOrderQueryDTO();
        queryDTO.setStatus(reqVO.getStatus());
        queryDTO.setOrderStatus(reqVO.getOrderStatus());
        queryDTO.setOrderType(reqVO.getType());
        PageResult<TradeOrderDO> pageResult = tradeOrderQueryService.getOrderPageByUserId(userId, pageParam, queryDTO);
        return success(tradeOrderQueryService.toPageResult(pageResult, false));
    }

    @GetMapping("/page-seller")
    @Operation(summary = "获得交易订单分页（卖家）")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<PageResult<AppTradeOrderPageVO>> getOrderPageForSeller(PageParam pageParam, TradeOrderQueryDTO queryDTO) {
        Long shopId = getShopId();
        PageResult<TradeOrderDO> pageResult = tradeOrderQueryService.getOrderPageByShopId(shopId, pageParam, queryDTO);
        return success(tradeOrderQueryService.toPageResult(pageResult, true));
    }

    @GetMapping("/page-rider")
    @Operation(summary = "获得交易订单分页（配送员）")
    @PreAuthorize("@mm.isRider()")
    public CommonResult<PageResult<AppTradeOrderPageVO>> getOrderPageForRider(PageParam pageParam, TradeOrderStatusDTO queryDTO) {
        ShopStaffVO shopStaffVO = shopStaffApi.getByUserId(getLoginUserId(), UserTypeEnum.MEMBER.getValue(), ShopStaffRoleEnum.RIDER.getValue());
        PageResult<TradeOrderDO> pageResult = tradeOrderQueryService.getOrderPageByStaffId(shopStaffVO.getShopId(), shopStaffVO.getId(), pageParam, queryDTO.getDineStatus());
        return success(tradeOrderQueryService.toPageResult(pageResult, false));
    }

    @GetMapping("/get-count")
    @Operation(summary = "获得交易订单数量（买家）")
    @PermitAll // 避免前端在未登录的情况下调用报 403 从而强制跳转登录页
    public CommonResult<Map<String, Integer>> getOrderCount() {
        Map<String, Integer> orderCount = Maps.newLinkedHashMapWithExpectedSize(7);
        Long userId = getLoginUserId();
        if (userId == null || userId <= 0) {
            // 全部
            orderCount.put("allCount", 0);
            // 待付款（未支付）
            orderCount.put("unpaidCount", 0);
            // 待使用/待提货/待核销/待服务
            orderCount.put("unusedCount", 0);
            // 待发货/待配送
            orderCount.put("undeliveredCount", 0);
            // 待收货/已送达
            orderCount.put("deliveredCount", 0);
            // 待评价
            orderCount.put("uncommentedCount", 0);
            // 售后退款
            orderCount.put("afterSaleCount", 0);
            return success(orderCount);
        }
        // 全部
        orderCount.put("allCount", tradeOrderQueryService.getOrderCountByUserId(userId, null, null, null));
        // 待付款（未支付）
        orderCount.put("unpaidCount", tradeOrderQueryService.getOrderCountByUserId(userId, null,
                TradeOrderStatusEnum.UNPAID.getStatus(), null));
        // 待发货/待配送
        orderCount.put("undeliveredCount", tradeOrderQueryService.getOrderCountByUserId(userId,
                Arrays.asList(DeliveryTypeEnum.EXPRESS.getType(), DeliveryTypeEnum.TAKE_OUT.getType()),
                TradeOrderStatusEnum.PAID.getStatus(), null));
        // 待使用/待提货/待核销/待服务
        orderCount.put("unusedCount", tradeOrderQueryService.getOrderCountByUserId(userId,
                Arrays.asList(DeliveryTypeEnum.PICK_UP.getType(), DeliveryTypeEnum.VERIFY.getType(), DeliveryTypeEnum.ONSITE.getType()),
                TradeOrderStatusEnum.DOING.getStatus(), null));
        // 待收货/已送达
        orderCount.put("deliveredCount", tradeOrderQueryService.getOrderCountByUserId(userId,
                Arrays.asList(DeliveryTypeEnum.EXPRESS.getType(), DeliveryTypeEnum.TAKE_OUT.getType()),
                TradeOrderStatusEnum.DOING.getStatus(), null));
        // 待评价
        orderCount.put("uncommentedCount", tradeOrderQueryService.getOrderCountByUserId(userId, null,
                TradeOrderStatusEnum.COMPLETED.getStatus(), false));
        // 售后退款（整单）
        orderCount.put("afterSaleCount", afterSaleService.getApplyingAfterSaleCountByUserId(userId, true));
        return success(orderCount);
    }


    @GetMapping("/get-count-rider")
    @Operation(summary = "获得交易订单数量（配送员）")
    @PermitAll // 避免前端在未登录的情况下调用报 403 从而强制跳转登录页
    public CommonResult<Map<String, Integer>> getOrderCountForRider() {
        Map<String, Integer> orderCount = Maps.newLinkedHashMapWithExpectedSize(4);
        Long userId = getLoginUserId();
        if (userId == null || userId <= 0) {
            orderCount.put("allCount", 0);
            orderCount.put("acceptedCount", 0);
            orderCount.put("doingCount", 0);
            orderCount.put("completeCount", 0);
            return success(orderCount);
        }
        ShopStaffVO shopStaffVO = shopStaffApi.getByUserId(userId, UserTypeEnum.MEMBER.getValue(), ShopStaffRoleEnum.RIDER.getValue());
        if (shopStaffVO == null) {
            orderCount.put("allCount", 0);
            orderCount.put("acceptedCount", 0);
            orderCount.put("doingCount", 0);
            orderCount.put("completeCount", 0);
            return success(orderCount);
        }
        // 全部
        orderCount.put("allCount", tradeOrderQueryService.getOrderCountByStaffId(shopStaffVO.getShopId(), shopStaffVO.getId(), (Integer) null));
        // 已接单，备餐中
        orderCount.put("acceptedCount", tradeOrderQueryService.getOrderCountByStaffId(shopStaffVO.getShopId(), shopStaffVO.getId(), DineStatusEnum.ACCEPTED.getValue()));
        // 进行中：已派单、已出餐、配送中
        orderCount.put("doingCount", tradeOrderQueryService.getOrderCountByStaffId(shopStaffVO.getShopId(), shopStaffVO.getId(), DineStatusEnum.ASSIGNED.getValue(), DineStatusEnum.PACKED.getValue(), DineStatusEnum.DELIVERING.getValue()));
        // 已送达
        orderCount.put("completeCount", tradeOrderQueryService.getOrderCountByStaffId(shopStaffVO.getShopId(), shopStaffVO.getId(), DineStatusEnum.ARRIVED.getValue()));
        return success(orderCount);
    }

    @PostMapping("/receive")
    @Operation(summary = "确认收货（买家）")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<Boolean> receiveOrder(@RequestParam("id") Long id) {
        tradeOrderUpdateService.receiveOrderByBuyer(getLoginUserId(), id);
        return success(true);
    }

    @GetMapping("/cancel")
    @Operation(summary = "取消交易订单（买家）")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<Boolean> cancelOrder(@RequestParam("id") Long id) {
        tradeOrderUpdateService.cancelOrderByBuyer(getLoginUserId(), id);
        return success(true);
    }

    @GetMapping("/delete")
    @Operation(summary = "删除交易订单（买家）")
    @Parameter(name = "id", description = "交易订单编号")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        tradeOrderUpdateService.deleteOrder(getLoginUserId(), id);
        return success(true);
    }

    @PostMapping("/delivery")
    @Operation(summary = "发货（卖家）")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<Boolean> deliveryOrder(@Valid @RequestBody TradeOrderDeliveryDTO dto) {
        Long shopId = getShopId();
        tradeOrderUpdateService.deliveryOrder(shopId, dto);
        return success(true);
    }

    @PostMapping("/accept")
    @Operation(summary = "接单（卖家）")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<Boolean> acceptOrder(@RequestParam("id") Long id) {
        Long shopId = getShopId();
        tradeOrderUpdateService.acceptOrder(shopId, id);
        return success(true);
    }

    @PostMapping("/pack")
    @Operation(summary = "出餐（卖家）")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<Boolean> packOrder(@RequestParam("id") Long id) {
        Long shopId = getShopId();
        tradeOrderUpdateService.packOrder(shopId, id);
        return success(true);
    }

    @PostMapping("/verify-by-verify-code")
    @Operation(summary = "订单核销（卖家）")
    @Parameter(name = "verifyCode", description = "核销码")
    @PreAuthorize("@mm.isVerifier()") // 核销员：商家或店员
    public CommonResult<Boolean> verifyOrderByVerifyCode(@RequestParam(value = "verifyCode", required = false) String verifyCode, @Valid @RequestBody AppTradeOrderVerifyReqVO reqVO) {
        String code = reqVO.getVerifyCode();
        if (StrUtil.isBlank(code)) {
            code = verifyCode;
        }
        if (StrUtil.isBlank(code)) {
            return error(BAD_REQUEST.getCode(), "核销码不能为空");
        }
        tradeOrderUpdateService.verifyOrderByMember(getLoginUserId(), code);
        return success(true);
    }

    @PostMapping("/pickup")
    @Operation(summary = "取餐（配送员）")
    @PreAuthorize("@mm.isRider()")
    public CommonResult<Boolean> pickupOrder(@RequestParam("id") Long id) {
        tradeOrderUpdateService.pickupOrderByRider(getLoginUserId(), id);
        return success(true);
    }

    @PostMapping("/arrive")
    @Operation(summary = "确认送达（配送员）")
    @PreAuthorize("@mm.isRider()")
    public CommonResult<Boolean> arriveOrder(@Valid @RequestBody TradeOrderArriveDTO dto) {
        tradeOrderUpdateService.receiveOrderByRider(getLoginUserId(), dto);
        return success(true);
    }

    @GetMapping("/get-by-verify-code")
    @Operation(summary = "查询核销码对应的订单（卖家）")
    @Parameter(name = "verifyCode", description = "核销码")
    @PreAuthorize("@mm.isVerifier()") // 核销员：商家或店员
    public CommonResult<AppTradeOrderDetailRespVO> getByVerifyCode(@RequestParam("verifyCode") String verifyCode) {
        TradeOrderDO tradeOrder = tradeOrderUpdateService.getByVerifyCode(getLoginUserId(), UserTypeEnum.MEMBER.getValue(), verifyCode);
        tradeOrder.setVerifyCode(""); // 不让商家看到核销码
        return toOrderDetailRespVO(tradeOrder);
    }

    @PostMapping("/comment/create")
    @Operation(summary = "创建交易订单评价（买家）")
    public CommonResult<Long> createOrderComment(@Valid @RequestBody AppTradeOrderEvaluationCreateReqVO createReqVO) {
        return success(tradeOrderUpdateService.createOrderCommentByMember(getLoginUserId(), createReqVO));
    }

    @GetMapping("/comment/my-page")
    @Operation(summary = "我的交易订单评价分页（买家）")
    public CommonResult<PageResult<AppTradeOrderEvaluationRespVO>> getMyOrderCommentPage(PageParam reqVO) {
        PageResult<ProductEvaluationRespDTO> result = productEvaluationApi.getMyCommentPage(getLoginUserId(), reqVO);
        return success(BeanUtils.toBean(result, AppTradeOrderEvaluationRespVO.class));
    }

    @GetMapping("/comment/get-count")
    @Operation(summary = "获得交易订单评价数量")
    @Parameter(name = "shopId", description = "店铺编号")
    @PermitAll
    public CommonResult<Map<String, Integer>> getOrderCommentCount(@RequestParam("shopId") Long shopId) {
        return success(productEvaluationApi.getCommentCount(shopId));
    }

    @GetMapping("/item/get")
    @Operation(summary = "获得交易订单项（买家）")
    @Parameter(name = "id", description = "交易订单项编号")
    public CommonResult<TradeOrderItemRespDTO> getOrderItem(@RequestParam("id") Long id) {
        TradeOrderItemDO item = tradeOrderQueryService.getOrderItem(getLoginUserId(), id);
        return success(TradeOrderConvert.INSTANCE.convert03(item));
    }

    @PostMapping("/item/create-comment")
    @Operation(summary = "创建交易订单项评价（买家）")
    public CommonResult<Long> createOrderItemComment(@Valid @RequestBody AppTradeOrderItemEvaluationCreateReqVO createReqVO) {
        return success(tradeOrderUpdateService.createOrderItemCommentByMember(getLoginUserId(), createReqVO));
    }

    private Long getShopId() {
        Long userId = getLoginUserId();
        return shopInfoApi.getShopIdByMemberUserId(userId);
    }

}
